package com.spc.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.spc.dao.OrderSettingDao;
import com.spc.pojo.OrderSetting;
import com.spc.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void add(List<OrderSetting> data) {
        if (data != null && data.size() > 0 ){
            //调用dao存储数据
            for (OrderSetting orderSetting : data) {
                //判断当前日期的数据是否在数据库中存在
                Date orderDate = orderSetting.getOrderDate();
                Long count = orderSettingDao.findCountByOrderDate(orderDate);
                if (count > 0 ){
                    //已经进行了预约设置
                    orderSettingDao.edit(orderSetting);
                }else {
                    //没有进行预约设置
                    orderSettingDao.add(orderSetting);
                }
            }
        }

    }

    //根据年月份查询预约设置数据
    @Override
    public List<Map> findByDate(String date) {
        String begin = date + "-1";
        String end = date + "-31";
        Map<String, String> map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        List<OrderSetting> list = orderSettingDao.findByDate(map);
        ArrayList<Map> result = new ArrayList<Map>();
        if (list != null && list.size()>0){
            for (OrderSetting orderSetting : list) {
                Map<String, Object> hashMap = new HashMap<>();
                hashMap.put("date",orderSetting.getOrderDate().getDate());
                hashMap.put("number",orderSetting.getNumber());
                hashMap.put("reservations",orderSetting.getReservations());
                result.add(hashMap);
            }
        }

        return result;
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //根据日期查询预约设置，判断是否有数据
        try {
            Date date = orderSetting.getOrderDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String date2 = sdf.format(date);
            Date d = sdf.parse(date2);
            orderSetting.setOrderDate(d);
            Long count = orderSettingDao.findCountByOrderDate(d);
            if (count > 0){
                //当前日期已经进行了预约设置，执行更新操作
                orderSettingDao.edit(orderSetting);
            }else {
                orderSettingDao.add(orderSetting);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
}
